using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XNASpriteLib
{
	public class Frame
	{
		private readonly Rectangle rect;
		private readonly Vector2 anchor;
		private RegistrationPoint[] registrationPoint;
		private Texture2D texture;

		public Frame(Vector2 anchor, Rectangle rect)
		{
			this.anchor = anchor;
			this.rect = rect;
		}

		public Frame(XmlNode node, GraphicsDevice graphicsDevice, Dictionary<string, Texture2D> textureDictionary)
		{
			if (node.Attributes != null)
			{
				if(node.Attributes["image"] != null)
				{
					string filename = node.Attributes["image"].Value;
					if (textureDictionary.ContainsKey(filename))
					{
						texture = textureDictionary[filename];
					}
					else
					{
						texture = Texture2D.FromStream(graphicsDevice, File.OpenRead(filename));
						textureDictionary.Add(filename, texture);
					}
				}
				else if(node.Attributes["imageIndex"] != null)
				{
					
				}
			}

			XmlNode currNode = node.FirstChild;
			while(currNode != null)
			{
				if(currNode.Name.ToLower() == "anchor")
				{
					anchor = new Vector2(float.Parse(currNode.Attributes["x"].Value), float.Parse(currNode.Attributes["y"].Value));
				}
				else if(currNode.Name.ToLower() == "rectangle")
				{
					int x, y, w, h;
					bool success = int.TryParse(currNode.Attributes["x"].Value, out x);
					success &= int.TryParse(currNode.Attributes["y"].Value, out y);
					success &= int.TryParse(currNode.Attributes["w"].Value, out w);
					success &= int.TryParse(currNode.Attributes["h"].Value, out h);
					if(success)
					{
						rect = new Rectangle(x, y, w, h);
					}
				}

				currNode = currNode.NextSibling;
			}
		}
		
		public Vector2 Anchor
		{
			get{ return anchor; }
		}

		public Rectangle Rect
		{
			get { return rect; }
		}

		public Vector2 TopLeft(Vector2 anchorMatch)
		{
			return anchorMatch - anchor;//new Vector2(anchor.X - (rect.Width / 2f), anchor.Y - (rect.Height / 2f));
		}

		public Texture2D Texture
		{
			get
			{
				return texture;
			}
			set
			{
				texture = value;
			}
		}
	}
}
